import java.io.*;
import java.net.*;
import java.util.*;

public class EStoreClient {
    private String serverHost;
    private int serverPort;
    private User currentUser;
    private Scanner scanner;

    public EStoreClient(String host, int port) {
        this.serverHost = host;
        this.serverPort = port;
        this.scanner = new Scanner(System.in);
    }

    private Object sendRequest(String requestType, Object requestData) {
        try (Socket socket = new Socket(serverHost, serverPort);
             ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
             ObjectInputStream ois = new ObjectInputStream(socket.getInputStream())) {

            oos.writeObject(requestType);
            oos.writeObject(requestData);
            oos.flush();

            return ois.readObject();

        } catch (Exception e) {
            System.err.println("请求失败: " + e.getMessage());
            return null;
        }
    }

    public boolean login(String username, String password) {
        Map<String, String> loginData = new HashMap<>();
        loginData.put("username", username);
        loginData.put("password", password);

        currentUser = (User) sendRequest("USER_LOGIN", loginData);
        return currentUser != null;
    }

    public boolean register(String username, String password, String email) {
        Map<String, String> registerData = new HashMap<>();
        registerData.put("username", username);
        registerData.put("password", password);
        registerData.put("email", email);

        User newUser = (User) sendRequest("USER_REGISTER", registerData);
        return newUser != null;
    }

    public void browseProducts() {
        List<Product> products = (List<Product>) sendRequest("GET_ALL_PRODUCTS", null);
        if (products != null && !products.isEmpty()) {
            System.out.println("\n=== 商品列表 ===");
            for (Product product : products) {
                System.out.println(product);
            }
        } else {
            System.out.println("没有找到商品");
        }
    }

    public void addToCart() {
        if (currentUser == null) {
            System.out.println("请先登录");
            return;
        }

        browseProducts();
        System.out.print("请输入要添加的商品ID: ");
        Integer productId = scanner.nextInt();
        System.out.print("请输入数量: ");
        Integer quantity = scanner.nextInt();
        scanner.nextLine();

        Map<String, Object> cartData = new HashMap<>();
        cartData.put("userId", currentUser.getId());
        cartData.put("productId", productId);
        cartData.put("quantity", quantity);

        Boolean result = (Boolean) sendRequest("ADD_TO_CART", cartData);
        if (result != null && result) {
            System.out.println("商品已添加到购物车");
        } else {
            System.out.println("添加商品失败");
        }
    }

    public void viewCart() {
        if (currentUser == null) {
            System.out.println("请先登录");
            return;
        }

        Cart cart = (Cart) sendRequest("GET_CART", currentUser.getId());
        System.out.println(cart != null ? cart : "购物车为空");
    }

    public void createOrder() {
        if (currentUser == null) {
            System.out.println("请先登录");
            return;
        }

        Order order = (Order) sendRequest("CREATE_ORDER", currentUser.getId());
        if (order != null) {
            System.out.println("订单创建成功:");
            System.out.println(order);
        } else {
            System.out.println("订单创建失败，请检查购物车和库存");
        }
    }

    public void viewMyOrders() {
        if (currentUser == null) {
            System.out.println("请先登录");
            return;
        }

        List<Order> orders = (List<Order>) sendRequest("GET_USER_ORDERS", currentUser.getId());
        if (orders != null && !orders.isEmpty()) {
            System.out.println("\n=== 我的订单 ===");
            for (Order order : orders) {
                System.out.println(order);
            }
        } else {
            System.out.println("没有找到订单");
        }
    }

    public void addProductAsAdmin() {
        if (currentUser == null || !"ADMIN".equals(currentUser.getRole())) {
            System.out.println("需要管理员权限");
            return;
        }

        System.out.print("请输入商品名称: ");
        String name = scanner.nextLine();
        System.out.print("请输入商品描述: ");
        String description = scanner.nextLine();
        System.out.print("请输入商品价格: ");
        Double price = scanner.nextDouble();
        System.out.print("请输入商品库存: ");
        Integer stock = scanner.nextInt();
        scanner.nextLine();

        Product product = new Product(null, name, description, price, stock);

        Map<String, Object> productData = new HashMap<>();
        productData.put("adminId", currentUser.getId());
        productData.put("product", product);

        Boolean result = (Boolean) sendRequest("ADD_PRODUCT", productData);
        if (result != null && result) {
            System.out.println("商品添加成功");
        } else {
            System.out.println("商品添加失败");
        }
    }

    public void viewAllOrders() {
        if (currentUser == null || !"ADMIN".equals(currentUser.getRole())) {
            System.out.println("需要管理员权限");
            return;
        }

        List<Order> orders = (List<Order>) sendRequest("GET_ALL_ORDERS", currentUser.getId());
        if (orders != null && !orders.isEmpty()) {
            System.out.println("\n=== 所有订单 ===");
            for (Order order : orders) {
                System.out.println(order);
            }
        } else {
            System.out.println("没有找到订单");
        }
    }

    public void showAdminMenu() {
        while (true) {
            System.out.println("\n=== 管理员菜单 ===");
            System.out.println("1. 添加商品");
            System.out.println("2. 浏览商品");
            System.out.println("3. 查看所有订单");
            System.out.println("4. 返回主菜单");
            System.out.print("请选择: ");

            int choice = scanner.nextInt();
            scanner.nextLine();

            switch (choice) {
                case 1:
                    addProductAsAdmin();
                    break;
                case 2:
                    browseProducts();
                    break;
                case 3:
                    viewAllOrders();
                    break;
                case 4:
                    return;
                default:
                    System.out.println("无效选择");
            }
        }
    }

    public void showUserMenu() {
        while (true) {
            System.out.println("\n=== 用户菜单 ===");
            System.out.println("1. 浏览商品");
            System.out.println("2. 添加到购物车");
            System.out.println("3. 查看购物车");
            System.out.println("4. 创建订单");
            System.out.println("5. 查看我的订单");
            System.out.println("6. 返回主菜单");
            System.out.print("请选择: ");

            int choice = scanner.nextInt();
            scanner.nextLine();

            switch (choice) {
                case 1:
                    browseProducts();
                    break;
                case 2:
                    addToCart();
                    break;
                case 3:
                    viewCart();
                    break;
                case 4:
                    createOrder();
                    break;
                case 5:
                    viewMyOrders();
                    break;
                case 6:
                    return;
                default:
                    System.out.println("无效选择");
            }
        }
    }

    public void start() {
        while (true) {
            System.out.println("\n=== 电商系统 ===");
            System.out.println("1. 登录");
            System.out.println("2. 注册");
            System.out.println("3. 退出");
            System.out.print("请选择: ");

            int choice = scanner.nextInt();
            scanner.nextLine();

            switch (choice) {
                case 1:
                    System.out.print("用户名: ");
                    String username = scanner.nextLine();
                    System.out.print("密码: ");
                    String password = scanner.nextLine();

                    if (login(username, password)) {
                        System.out.println("登录成功！欢迎 " + currentUser.getUsername());
                        if ("ADMIN".equals(currentUser.getRole())) {
                            showAdminMenu();
                        } else {
                            showUserMenu();
                        }
                    } else {
                        System.out.println("登录失败！");
                    }
                    break;

                case 2:
                    System.out.print("用户名: ");
                    String newUsername = scanner.nextLine();
                    System.out.print("密码: ");
                    String newPassword = scanner.nextLine();
                    System.out.print("邮箱: ");
                    String email = scanner.nextLine();

                    if (register(newUsername, newPassword, email)) {
                        System.out.println("注册成功！");
                    } else {
                        System.out.println("注册失败！用户名可能已存在");
                    }
                    break;

                case 3:
                    System.out.println("再见！");
                    sendRequest("EXIT", null);
                    return;

                default:
                    System.out.println("无效选择");
            }
        }
    }

    public static void main(String[] args) {
        EStoreClient client = new EStoreClient("localhost", 8888);
        client.start();
    }
}